package service

import (
	"github.com/gin-gonic/gin"
	appConst "poem-server/comm/const"
	"poem-server/comm/global"
	"poem-server/comm/request"
	"poem-server/comm/response"
	"poem-server/mvc/dao/model"
	"poem-server/mvc/dao/query"
	utils "poem-server/utils/bean"
	"poem-server/utils/message/sms"
)

type UserService struct{}

func (u UserService) LoginByPhone(ctx *gin.Context, info request.PhoneVo) bool {
	//TODO implement me
	panic("implement me")
}

func (u UserService) LoginByUserName(info request.UsernameVo) *model.User {
	username := info.Username
	password := info.Password
	userDao := query.Use(global.App.Mysql).User
	user, err := userDao.Where(userDao.Username.Eq(username), userDao.Password.Eq(password)).First()
	if err != nil || user == nil {
		return nil //没找到或者出错了则返回空的
	}
	//登录成功就把当前用户信息存入session
	utils.BeanCopy(user, &global.UserNow)
	return user
}

func (u UserService) RegisterByPhone(ctx *gin.Context, info request.PhoneVo) bool {
	phone := info.Phone
	code := info.Code
	// TODO 查询该账号是否已经注册
	userDao := query.Use(global.App.Mysql).User
	count, err := userDao.Where(userDao.Phone.Eq(phone)).Count()
	if err != nil {
		response.DBFail(ctx, err)
		return false
	}
	if count >= 1 { //已经注册
		return false
	}
	//TODO 对比验证码是否匹配
	key := appConst.REGISTER_CODE + phone
	codeTrue := global.App.Redis.Get(key).Val()
	if code != codeTrue {
		return false
	}
	// TODO 插入数据库
	var user *model.User
	utils.BeanCopy(&info, user)
	err2 := userDao.Create(user)
	if err != nil {
		response.DBFail(ctx, err2)
		return false
	}

	return true
}

func (u UserService) GetInfo(userId int32) model.User {
	return model.User{
		ID:       1,
		Username: "青青子衿",
		Password: "123456",
		Gender:   1,
	}
}

func (u UserService) UpdateInfo(user request.UserInfoVo) bool {
	userDao := query.Use(global.App.Mysql).User
	updates, err := userDao.Where(userDao.ID.Eq(global.UserNow.UserID)).Updates(user)
	if err != nil {
		return false
	}
	if updates.RowsAffected == 0 {
		return false
	}
	return true
}

func (u UserService) RegisterByUserName(ctx *gin.Context, info request.UsernameVo) bool {
	username := info.Username

	// TODO 查询账号是否注册
	userDao := query.Use(global.App.Mysql).User
	count, err := userDao.Where(userDao.Username.Eq(username)).Count()
	if err != nil {
		response.DBFail(ctx, err)
		return false
	}
	if count >= 1 {
		return false
	}

	// TODO 插入数据库
	var user *model.User
	utils.BeanCopy(&info, user)
	err2 := userDao.Create(user)
	if err2 != nil {
		response.DBFail(ctx, err2)
		return false
	}
	return true
}

func (u UserService) SendCode(phone string) bool {
	// TODO 生成验证码
	code := "1234"
	messages := sms.MessageInfo{
		Phone:   phone,
		Message: code,
	}
	// TODO 调用ali 发送短信功能
	err := sms.SendMessage(messages)
	if err != nil {
		return false
	}
	return true
}
